﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Input;

using DanielVaughan.ComponentModel;
using DanielVaughan.Windows;

namespace CalciumTemplateApp.Views.Examples
{
	public class ValidationPivotViewModel : UserViewModel
	{
		public ValidationPivotViewModel() : base("validation")
		{
			submitCommand = new DelegateCommand(
				delegate
				{
					IsComplete(
						() => MessageService.ShowMessage("Data Submitted."),
						() => MessageService.ShowMessage("Please complete the form."),
						obj => MessageService.ShowError("An error occured: " + obj.Message));
				});

			NavigatingFrom += HandleNavigatingFrom;
		}

		void HandleNavigatingFrom(object sender, CancelEventArgs e)
		{
			IsComplete(() => Debug.WriteLine("Data Submitted."),
						() =>
							{
								bool answer = MessageService.AskYesNoQuestion("Form is not valid. Continue?");
								if (!answer)
								{
									e.Cancel = true;
								}
							},
						obj => MessageService.ShowError("An error occured: " + obj.Message));
		}


		readonly DelegateCommand submitCommand;

		public ICommand SubmitCommand
		{
			get
			{
				return submitCommand;
			}
		}

		string validatedString1;

		[Validate]
		public string ValidatedString1
		{
			get
			{
				return validatedString1;
			}
			set
			{
				Assign(() => ValidatedString1, ref validatedString1, value);
			}
		}

		string validatedString2;

		[Validate]
		public string ValidatedString2
		{
			get
			{
				return validatedString2;
			}
			set
			{
				Assign(() => ValidatedString2, ref validatedString2, value);
			}
		}

		protected override IEnumerable<DataValidationError> GetPropertyErrors(
			string propertyName, object value)
		{
			if (!string.IsNullOrWhiteSpace((string)value))
			{
				yield break;
			}

			switch (propertyName)
			{
				case "ValidatedString1":
					yield return new DataValidationError(1,
						"ValidatedString1 is required.");
					break;
				case "ValidatedString2":
					yield return new DataValidationError(2,
						"ValidatedString2 is required.");
					break;
			}
			yield break;
		}
	}
}
